package org.example.aidemo.service.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class AutoNaviService {

    private static final String API_KEY = "d0cbc87c48295466b53450a18cddaa98";
    private static final String REVERSE_GEOCODE_URL = "https://restapi.amap.com/v3/geocode/regeo";

    @Autowired
    private RestTemplate restTemplate;

    public String getAddressByCoordinates(String longitude, String latitude) {
        try {
            String url = REVERSE_GEOCODE_URL + "?key=" + API_KEY + "&location=" + longitude + "," + latitude;
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            // 解析JSON响应
            String responseBody = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            if ("1".equals(jsonObject.getString("status"))) {
                // 提取格式化地址
                String formattedAddress = jsonObject.getJSONObject("regeocode").getString("formatted_address");
                return formattedAddress;
            } else {
                return "地址解析失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "未知地址";
        }
    }
}